<template>
  <n-drawer v-model:show="isDrawer" :width="width" :placement="placement">
    <n-drawer-content :title="title" closable>
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="100"
      >
        <n-form-item label="角色名称" path="roleName">
          <n-input placeholder="请输入名称" v-model:value="formParams.roleName" />
        </n-form-item>
        <n-form-item label="角色编码" path="roleCode">
          <n-input placeholder="请输入角色编码" v-model:value="formParams.roleCode" />
        </n-form-item>
        <n-form-item label="说明" path="roleDesc">
          <n-input placeholder="请输入说明" v-model:value="formParams.roleDesc" />
        </n-form-item>
        <n-form-item label="菜单权限" path="roleDesc">
          <n-layout>
            <div class="py-3 menu-list">
              <n-tree
                block-line
                cascade
                checkable
                :virtual-scroll="true"
                :data="treeData"
                :expandedKeys="expandedKeys"
                :checked-keys="checkedKeys"
                key-field="id"
                label-field="title"
                style="max-height: 950px; overflow: hidden"
                @update:checked-keys="checkedTree"
                @update:indeterminate-keys="indeterminateTree"
                @update:expanded-keys="onExpandedKeys"
              />
            </div>
            <n-space>
              <n-button type="info" ghost icon-placement="left" @click="packHandle">
                全部{{ expandedKeys.length ? '收起' : '展开' }}
              </n-button>

              <n-button type="info" ghost icon-placement="left" @click="checkedAllHandle">
                全部{{ checkedAll ? '取消' : '选择' }}
              </n-button>
            </n-space>
          </n-layout>
        </n-form-item>
      </n-form>

      <template #footer>
        <n-space>
          <n-button type="primary" :loading="subLoading" @click="formSubmit">提交</n-button>
          <n-button @click="handleReset">重置</n-button>
        </n-space>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts">
  import { defineComponent, reactive, ref, toRefs } from 'vue';
  import { useMessage } from 'naive-ui';
  import { getTreeAll } from '@/utils';
  import { addObj } from '@/api/system/role';
  import { getMenuList } from '@/api/system/menu';
  const rules = {
    label: {
      required: true,
      message: '请输入角色名称',
      trigger: 'blur',
    },
    path: {
      required: true,
      message: '请输入路径',
      trigger: 'blur',
    },
  };
  export default defineComponent({
    name: 'CreateDrawer',
    components: {},
    props: {
      title: {
        type: String,
        default: '创建角色',
      },
      width: {
        type: Number,
        default: 450,
      },
    },
    async onMounted() {
      const treeMenuList = await getMenuList();
      this.expandedKeys = treeMenuList.map((item) => item.id);
      this.treeData = treeMenuList;
    },
    emits: ['refreshTable'],
    setup(_props, context) {
      const expandedKeys = ref([]);
      const treeData = ref([]);
      const checkedAll = ref(false);
      const checkedKeys = ref();
      const indeterminate = ref();
      checkedKeys.value = [];
      const message = useMessage();
      const formRef: any = ref(null);
      const menuList = async () => {
        const treeMenuList = await getMenuList();
        expandedKeys.value = treeMenuList.map((item) => item.id);
        treeData.value = treeMenuList;
      };
      menuList();
      const defaultValueRef = () => ({
        roleName: '',
        roleCode: '',
        roleDesc: '',
        menuIds: [1],
      });
      const state = reactive({
        isDrawer: false,
        subLoading: false,
        formParams: defaultValueRef(),
        placement: 'right' as const,
        alertText:
          '该功能主要实时预览各种布局效果，更多完整配置在 projectSetting.ts 中设置，建议在生产环境关闭该布局预览功能。',
      });

      function openDrawer() {
        state.isDrawer = true;
      }

      function closeDrawer() {
        state.isDrawer = false;
      }

      function formSubmit() {
        formRef.value.validate(async (errors) => {
          if (!errors) {
            if (indeterminate.value != null) {
              state.formParams.menuIds = checkedKeys.value.concat(indeterminate.value);
            }
            await addObj(state.formParams);
            message.success('添加成功');
            context.emit('refreshTable');
            handleReset();
            closeDrawer();
          } else {
            message.error('请填写完整信息');
          }
        });
      }

      function handleReset() {
        formRef.value.restoreValidation();
        state.formParams = Object.assign(state.formParams, defaultValueRef());
      }
      function packHandle() {
        if (expandedKeys.value.length) {
          expandedKeys.value = [];
        } else {
          expandedKeys.value = treeData.value.map((item: any) => item.id) as [];
        }
      }

      function checkedAllHandle() {
        if (!checkedAll.value) {
          checkedKeys.value = getTreeAll(treeData.value);
          checkedAll.value = true;
        } else {
          checkedKeys.value = [];
          checkedAll.value = false;
        }
      }
      function checkedTree(keys) {
        checkedKeys.value = [...keys];
      }
      function indeterminateTree(keys) {
        indeterminate.value = [...keys];
      }
      function onExpandedKeys(keys) {
        expandedKeys.value = keys;
      }
      return {
        ...toRefs(state),
        formRef,
        rules,
        formSubmit,
        handleReset,
        openDrawer,
        closeDrawer,
        expandedKeys,
        packHandle,
        checkedAllHandle,
        checkedAll,
        checkedKeys,
        treeData,
        checkedTree,
        onExpandedKeys,
        indeterminateTree,
      };
    },
  });
</script>
